﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Linq;

namespace Nfe.Extension.Validator
{
    public class Validator
    {
        public string xmlnamespace { get; set; }
        private string pathToXsdl;

        public Validator(string _pathToXsdl)
        {
            pathToXsdl = _pathToXsdl;

            this.xmlnamespace = "http://www.portalfiscal.inf.br/nfe";
        }

        /// <summary>
        /// Validates a Xml Document
        /// </summary>
        /// <param name="strXMLDoc">Current Xml Document to be validated</param>
        /// <returns>A string representing all messages from schema validation</returns>
        public string Validate(string strXMLDoc)
        {
            string errorMsg = "";
            try
            {
                // Text reader object
                var tr = new XmlTextReader(pathToXsdl);

                var xsc = new XmlSchemaSet();

                var xmlReaderSettings = new XmlReaderSettings();

                xsc.Add(xmlnamespace, XmlReader.Create(tr, xmlReaderSettings));

                var xmlDoc = XDocument.Parse(strXMLDoc);

                xmlDoc.Validate(xsc, (o, e) =>
                {
                    errorMsg += e.Message + "\n";
                });
            }
            catch (Exception error)
            {
                // XML Validation failed
                errorMsg = String.Format("XML validation failed. Error Message: {0}", error.Message);
            }

            return errorMsg;
        }

        /// <summary>
        /// Validates a Xml Document
        /// </summary>
        /// <param name="vXmlDoc">Current Xml Document to be validated</param>
        /// <returns>A list of strings representing each messages from schema validation</returns>
        public List<string> ValidateToList(string vXmlDoc)
        {
            List<string> lisMessages = new List<string>();

            try
            {
                // Text reader object
                var tr = new XmlTextReader(pathToXsdl);

                var xsc = new XmlSchemaSet();

                var xmlReaderSettings = new XmlReaderSettings();

                xsc.Add(xmlnamespace, XmlReader.Create(tr, xmlReaderSettings));

                var xmlDoc = XDocument.Parse(vXmlDoc);

                xmlDoc.Validate(xsc, (obj, Current) =>
                {
                    lisMessages.Add(Current.Message);
                });
            }
            catch (Exception vErr)
            {
                lisMessages.Add(String.Format("XML validation failed: {0}", vErr.Message));
            }

            return lisMessages;
        }
    }
}
